#include <my_header.h>
#include <string.h>

/* Usage: 
 * 递归遍历目录，统计目录数与文件数
 * 检查文件是否以.txt结尾
 * 编译成功的测试命令 ./01_Dir_Recurse ../../..
 * */

static int dirs = 0;
static int files = 0;
static int count_size = 0;

void DFS_print(char* path, int width);

int main(int argc, char *argv[]){                                  
    ARGS_CHECK(argc, 2);
    
    // 打印根目录名称
    printf("%s \n", argv[1]);

    DFS_print(argv[1], 1);
    printf("\n%d directories, %d files, .txt size: %d bytes \n", dirs, files, count_size);

    return 0;
}
// 深度优先搜索打印目录树
void DFS_print(char* path, int width){
    // 打开文件，检查错误
    DIR* dirp = opendir(path);
    if(dirp == NULL){
        return;
    }

    struct dirent* pdirent;

    while(1){
        // Read directory
        pdirent = readdir(dirp);
        if(pdirent == NULL){
            break;
        }

        // Ignore "." and ".."
        if(strcmp(pdirent->d_name, ".") == 0 || 
           strcmp(pdirent->d_name, "..") == 0){
            continue;
        }
        
        // Print space before directory
        printf("%*s", width * 4, "");
        printf("%s\n", pdirent->d_name);
       
        char next_path[1024];
        memset(next_path, 0, sizeof(next_path));
        // Avoid using sprintf as it may cause buffer overlap when rewriting 'path'
        snprintf(next_path, sizeof(next_path), "%s/%s", path, pdirent->d_name);
        
        // Initialize the stat
        struct stat file_stat;
        stat(next_path, &file_stat);

        // Check the ptr type
        if(pdirent->d_type == DT_DIR){
            dirs++;
            DFS_print(next_path, width + 1);
        }
        else{
            files++;
            if(pdirent->d_type == DT_REG && 
               strlen(pdirent->d_name) >= 4 && 
               strcmp(pdirent->d_name + strlen(pdirent->d_name) - 4, ".txt") == 0){
                count_size += file_stat.st_size;
            }
        }
    }

    closedir(dirp);
}


